import datetime
from rest_framework.authentication import TokenAuthentication, get_authorization_header
from rest_framework.exceptions import AuthenticationFailed
from rest_framework_jwt.utils import jwt_decode_handler

from weixin_caipu.settings import AUTH_TOKEN_AGE
from apps.uitls.time_util import TimeUtil


class ExpiringTokenAuthentication(TokenAuthentication):
    def authenticate_credentials(self, key):
        model = self.get_model()
        try:
            token = model.objects.select_related('user').get(key=key)
        except model.DoesNotExist:
            raise AuthenticationFailed(_('Invalid token.'))
        if not token.user.is_active:
            raise AuthenticationFailed(_('User inactive or deleted.'))

        now = int(TimeUtil.string2time_stamp(str(datetime.datetime.now())))
        token_created = int(TimeUtil.string2time_stamp(str(token.created)))
        # 满足条件的话，就表示token已失效，提示用户重新登录刷新token.
        if now - token_created > AUTH_TOKEN_AGE:
            raise AuthenticationFailed('Token has expired')

        return token.user, token


def Verify(jwt):
    try:
        user = jwt_decode_handler(jwt)
        return user
    except:
        return False
